import { Injectable } from '@angular/core';

import {HttpClient, HttpHeaders} from "@angular/common/http";



import {Observable,of} from "rxjs";
import {catchError, map, tap } from "rxjs/operators";


import {MessageService} from "../messages/message.service";
import {HeroObject} from "../model/heroObject";


const httpOptions = {
  headers : new HttpHeaders({ 'Content-Type': 'application/json' })
};

//把这个类标记为依赖注入系统
@Injectable({
  providedIn: 'root'
})
export class HomeService {

   //模拟接口
   private heroURL : string = "api/herolist";



  constructor(
    private http:HttpClient,
    private messageService:MessageService) {

  }

  //获取数据列表
  getHeroList() : Observable<HeroObject[]> {
     return this.http.get<HeroObject[]>(this.heroURL).pipe(
       tap(_ =>this.log('获取到网络的英雄列表数据')),
       catchError(this.handelError<HeroObject[]>('getHeroList',[]))
     );
   }

   //获取单个数据
   getSignleDetailWithId(id : number) : Observable<HeroObject> {

       const url = `${this.heroURL}/${id}`;

       return this.http.get<HeroObject>(url).pipe(
            tap(_ => this.log(`获取详情数据：id=${id}`)),
            catchError(this.handelError<HeroObject>('getSignleDetailWithId'))
       );

    }

    //更新
  updateHero(hero:HeroObject):Observable<any>{

    return this.http.put<HeroObject>(this.heroURL,hero,httpOptions).pipe(

      tap(hero => this.log(`更新 英雄  ${hero.name} id=${hero.id}`)),

      catchError(this.handelError<any>('updateHero'))
    );
  }


  //增加数据
  addHeroEvent(object : HeroObject):Observable<HeroObject>{
      return this.http.post<HeroObject>(this.heroURL,object,httpOptions).pipe(
        tap((hero : HeroObject) => this.log(`增加 英雄  ${hero.name} id = ${hero.id}`)),
        catchError(this.handelError<HeroObject>('addHeroEvent'))
      );
  }

  //删除数据
  deleteHeroEvent(object : HeroObject | number) : Observable<HeroObject>{

    const  id = typeof object === "number"?object:object.id;

    return this.http.delete<HeroObject>(this.heroURL,httpOptions).pipe(
      tap(hero => this.log(`删除英雄 ${hero.name} id=${id}`)),
      catchError(this.handelError<HeroObject>('deleteHero'))
    );
  }


  //搜索数据
  searchHeroEvent(name : string) : Observable<HeroObject[]>{
       if(!name.trim()){
         return of([]);
       }
       return this.http.get<HeroObject[]>(`${this.heroURL}/?name=${name}`).pipe(
         tap(_ => this.log(`搜索到英雄 ${name}`)),
         catchError(this.handelError<HeroObject[]>('searchHeroEvent',[]))
       );
  }




   private log(message:string){
      this.messageService.addMessage(message);
    };


  //错误处理
   private handelError<T>(operation = "operation",result ?: T){
     return (error : any) : Observable<T> => {

        console.log(error);

        this.log(`${operation} Failid: ${error.message}`);

        return of(result as T);
     };
   };



}
